package cn.changeforyou.web.cloud.auth.util;

import cn.changeforyou.web.cloud.auth.exception.AuthExceptionEnum;
import cn.changeforyou.base.exception.ExceptionFactory;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Map;

/**
 * @md-model springboot.springSecurity.jwt
 * JwtToken生成的工具类
 * JWT token的格式：header.payload.signature
 * header的格式（算法、token的类型）：
 * {"alg": "HS512","typ": "JWT"}
 * payload的格式（用户名、创建时间、生成时间）：
 * {"sub":"wang","created":1489079981393,"exp":1489684781}
 * signature的生成算法：
 * HMACSHA512(base64UrlEncode(header) + "." +base64UrlEncode(payload),secret)
 * @author XWY
 */
@Component
@ConfigurationProperties(prefix = "secure.jwt")
public class JwtTokenUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JwtTokenUtil.class);

    /**
     * 密钥
     */
    private String secret;

    /**
     * 过期时间 -1表示不设置
     */
    private Double expirationMinutes;

    /**
     * jwt的header头
     */
    private String tokenHead = "Authorization";
    private static final String ROLE_CLAIMS = "role";

    /**
     * 负责生成JWT的token
     * 携带数据：用户名、角色集合
     */
    private String generateToken(Map<String, Object> claims, Map<String, Object> role) {
        return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
    }

    /**
     * 负责生成JWT的token
     */
    public String generateToken(Map<String, Object> claims) {
        return Jwts.builder()
            .setClaims(claims)
            .setExpiration(generateExpirationDate())
            .signWith(SignatureAlgorithm.HS512, secret)
            .compact();
    }

    /**
     * 从token中获取JWT中的负载
     */
    public Claims getClaimsFromToken(String token) {
        Claims claims = null;
        try {
            claims = Jwts.parser()
                .setSigningKey(secret)
                .parseClaimsJws(token)
                .getBody();
        } catch (ExpiredJwtException e){
            throw ExceptionFactory.jsonException(AuthExceptionEnum.TOKEN_EXPIRED);
        }catch (Exception e) {
            throw ExceptionFactory.jsonException(AuthExceptionEnum.TOKEN_ERROR);
        }
        return claims;
    }

    /**
     * 生成token的过期时间
     */
    private Date generateExpirationDate() {
        return new Date(System.currentTimeMillis() + (long)(expirationMinutes * 1000 * 60));
    }

    /**
     * 判断token是否已经失效
     */
    private boolean isTokenExpired(String token) {
        Date expiredDate = getExpiredDateFromToken(token);
        return expiredDate.before(new Date());
    }

    /**
     * 从token中获取过期时间
     */
    private Date getExpiredDateFromToken(String token) {
        Claims claims = getClaimsFromToken(token);
        return claims.getExpiration();
    }

    public String getSecret() {
        return secret;
    }

    public void setSecret(String secret) {
        this.secret = secret;
    }

    public Double getExpirationMinutes() {
        return expirationMinutes;
    }

    public void setExpirationMinutes(Double expirationMinutes) {
        this.expirationMinutes = expirationMinutes;
    }

    public String getTokenHead() {
        return tokenHead;
    }

    public void setTokenHead(String tokenHead) {
        this.tokenHead = tokenHead;
    }
}
